import React, { Component } from 'react';
import FontIcon from 'material-ui/FontIcon';
import RaisedButton from 'material-ui/RaisedButton';
import CircularProgress from 'material-ui/CircularProgress';

import { connect } from 'react-redux';
import { push } from 'react-router-redux';

import Corp from '../Utils/Corp';
import CONFIG from '../../config';
import EditUserImg from './EditUserImg';
import EditBasicInfo from './EditBasicInfo';
import EditOtherInfo from './EditOtherInfo';
import { dateFormat } from '../Utils/Helper';
import EditSchoolInfo from './EditSchoolInfo';
import { tokenExpired, getData } from '../../redux/actions/LayoutsAc';
import { checkHttpStatus, parseJSON, postJsonMethod } from '../../redux/Helper';

class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // 开启图片剪裁会话框
      method: 'userImg',
      openCorp: false,
      error: {},
      isFetching: false,
      userImg: this.props.userData.user_img,
      userName: this.props.userData.user_name,
      college: this.props.userData.college,
      professional: this.props.userData.professional,
      studentId: this.props.userData.student_id,
      collegeEntry: this.props.userData.college_entry,
      sex: this.props.userData.sex,
      state: this.props.userData.state,
      birth: this.props.userData.birth,
      notes: this.props.userData.notes,
    }
  }
  
  componentWillMount() {
  	if (!this.props.isCurrentUser) {
      this.props.replaceTo('/i');
    }
  }

  componentDidMount() {
    if (!this.props.isCurrentUser) {
      this.props.replaceTo('/i');
    }
  }

  /**
   * 修改text表单的值
   */
  handleChangeText = (n, e, v) => {
    this.setState({[n]: v});
  };

  /**
   * 修改日期表单的值
   */
  handleChangeDate = (n, e, v) => {
    this.setState({[n]: dateFormat(v)});
  };
  
  /**
   * 修改选择框表单的值
   */
  handleChangeSelect = (name, event, index, value) => {
    this.setState({[name]: value});
  };

  handleChangeSelectValue = (name, value) => {
    this.setState({[name]: value});
  };

  /**
   * 开启图片编辑器
   */
  handleOpen = (method) => {
    this.setState({method: method, openCorp: true});
  };

  /**
   * 关闭图片编辑器
   */
  handleClose = () => {
    this.setState({openCorp: false});
  };

  /**
   * 关闭图片编辑器前返回处理好的数据
   */
  handleChange = (e, name, value, canvas) => {
    this.setState({[name]: value});
  };

  /**
   * 更新数据
   */
  handleEdit = () => {
    let data = {
      user_img: this.state.userImg,
      user_name: this.state.userName,
      college: this.state.college,
      professional: this.state.professional,
      student_id: this.state.studentId,
      college_entry: this.state.collegeEntry,
      sex: this.state.sex,
      state: this.state.state,
      birth: this.state.birth,
      notes: this.state.notes,
    };

    if (this.state.userImgUploadCanvas) {
      var dataURL = this.state.userImgUploadCanvas.toDataURL('image/jpeg', 0.6);
      data.user_img = dataURL;
    }

    this.setState({isFetching: true});
    let request = `?token=${this.props.token}`;
    let url = `${CONFIG.apiHost}/api/user/${this.props.userId}${request}`;
    fetch(url, postJsonMethod(data))
    .then(checkHttpStatus)
    .then(parseJSON)
    .then(res => {
      this.setState({isFetching: false});
      this.props.dispatch(getData(this.props.userId, this.props.token));
      this.sendReloadEvent();
      this.props.pushTo(`/user/${this.props.userId}`);
    })
    .catch(e => {
      Promise.resolve(e.res.json()).then(v => {
        this.setState({isFetching: false, error: v.msg});
        if (v.error) {
          this.props.tokenExpired();
        }
      })
    })
  };

  /**
   * 发送重载事件至由我发布页面
   */
  sendReloadEvent = () => {
    var evt = new CustomEvent('reloadUserProfile');
    window.dispatchEvent(evt);
  };

  render() {
  	return (
  	  <div style={styles.body}>

        <EditUserImg
          error={this.state.error}
          userImg={this.state.userImg}
          userName={this.state.userName}
          handleOpen={this.handleOpen}
          handleChangeText={this.handleChangeText}
        />

        <div style={styles.step}> 学生认证 </div>

        <EditSchoolInfo 
          isEdit={true}
          error={this.state.error}
          college={this.state.college}
          professional={this.state.professional}
          studentId={this.state.studentId}
          collegeEntry={this.state.collegeEntry}
          handleChangeText={this.handleChangeText}
          handleChangeSelect={this.handleChangeSelect}
          handleChangeSelectValue={this.handleChangeSelectValue}
        />

        <div style={styles.step}> 基本信息 </div> 

        <EditBasicInfo 
          sex={this.state.sex}
          state={this.state.state}
          birth={this.state.birth}
          handleChangeText={this.handleChangeText}
          handleChangeDate={this.handleChangeDate}
          handleChangeSelect={this.handleChangeSelect}
        />

        <div style={styles.step}> 其他信息 </div>

        <EditOtherInfo 
          error={this.state.error}
          notes={this.state.notes}
          handleChangeText={this.handleChangeText}
        />

        <div style={styles.step}>
          <RaisedButton
            labelPosition="before"
            primary={true}
            icon={this.state.isFetching ? '' : <FontIcon className="icon-check" />}
            onClick={this.handleEdit.bind(this)}
            label={this.state.isFetching ? '' : '修改'}
            children={this.state.isFetching 
              ? <CircularProgress 
                style={{margin: 6}} 
                size={24} 
                color="#fff"/> 
              : ''
            }
          />
        </div>

        <Corp 
          open={this.state.openCorp}
          method={this.state.method}
          handleClose={this.handleClose}
          handleChange={this.handleChange}
          isSmallViewport={this.props.isSmallViewport}
          handleOpenSnackbar={this.props.handleOpenSnackbar}
        />
      </div>
  	);
  }
};

const styles = {
  body: {
    maxWidth: 728,
    marginLeft: 'auto',
    marginRight: 'auto'
  },
  step: {
    textAlign: 'center', 
    padding: 16, 
    fontSize: 16, 
    color: 'rgb(117,117,117)'
  },
};

const mapStateToProps = (state) => ({
  data: state.user,
  isSmallViewport: state.layouts.isSmallViewport
});

export default connect(mapStateToProps)(Edit);